﻿
/* 异步请求结果返回状态码 */
var ResultStatus = { OK: 200, Failed: 500, Unauthorized: 401,NotFound:404 };

Date.prototype.format = function (format) {
    var o =
        {
            "M+": this.getMonth() + 1, //month
            "d+": this.getDate(),    //day
            "H+": this.getHours(),   //hour
            "m+": this.getMinutes(), //minute
            "s+": this.getSeconds(), //second
            "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
            "S": this.getMilliseconds() //millisecond
        };
    if (/(y+)/.test(format))
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    return format;
};
Array.prototype.where = function (predicate) {
    var arr = this;
    var retArr = [];
    for (var i = 0; i < arr.length; i++) {
        var item = arr[i];
        if (predicate(item)) {
            retArr.push(item);
        }
    }
    return retArr;
};
Array.prototype.select = function (selector) {
    var arr = this;
    var retArr = [];
    for (var i = 0; i < arr.length; i++) {
        var item = arr[i];
        retArr.push(selector(item));
    }
    return retArr;
};
Array.prototype.first = function (predicate) {
    var arr = this;
    var retArr = [];
    for (var i = 0; i < arr.length; i++) {
        var item = arr[i];
        if (predicate(item)) {
            return item;
        }
    }
    return retArr;
};
//去重
Array.prototype.hovercUnique = function (arr) {
    var result = [], hash = {};
    for (var i = 0, elem; (elem = arr[i]) != null; i++) {
        if (!hash[elem]) {
            result.push(elem);
            hash[elem] = true;
        }
    }
    return result;

};

/* $dh */
(function ($) {

    
    var $dh = {};

    /* 返回 json 数据 */
    $dh.get = function (url, data, callback) {
        if ($.isFunction(data)) {
            callback = data;
            data = undefined;
        }

        url = parseUrl(url);
        var ret = execAjax("GET", url, data, callback);
        return ret;
    }
    $dh.post = function (url, data, callback) {
        if ($.isFunction(data)) {
            callback = data;
            data = undefined;
        }

        var ret = execAjax("POST", url, data, callback);
        return ret;
    }

    $dh.alert = function (msg, callBack) {
        layerAlert(msg, callBack);
    }
    $dh.confirm = function (msg, callBack) {
        layerConfirm(msg, callBack);
    }
    $dh.msg = function (msg) {
        layerMsg(msg);
    }

    $dh.reload = function () {
        location.reload();
        return false;
    }

    /* 将当前 url 的参数值 */
    $dh.getQueryParam = function (name) {
        if (name === null || name === undefined || name === "")
            return "";
        name = ("" + name).toLowerCase();
        var search = location.search.slice(1);
        var arr = search.split("&");
        for (var i = 0; i < arr.length; i++) {
            var ar = arr[i].split("=");
            if (ar[0].toLowerCase() == name) {
                if (unescape(ar[1]) == 'undefined') {
                    return "";
                } else {
                    return unescape(ar[1]);
                }
            }
        }
        return "";
    }
    /* 将当前 url 参数转成一个 js 对象 */
    $dh.getQueryParams = function () {
        var params = {};
        var loc = window.location;
        var se = decodeURIComponent(loc.search);

        if (!se) {
            return params;
        }

        var paramsString;
        paramsString = se.substr(1);//将?去掉
        var arr = paramsString.split("&");
        for (var i = 0; i < arr.length; i++) {
            var item = arr[i];
            var index = item.indexOf("=");
            if (index == -1)
                continue;
            var paramName = item.substr(0, index);
            if (!paramName)
                continue;
            var value = item.substr(index + 1);
            params[paramName] = value;
        }
        return params;
    }

    /* optionList: [{"Value" : "1", "Text" : "开发部"},{"Value" : "2", "Text" : "测试部"}] */
    $dh.getOptionTextByValue = function (optionList, value, valuePropName, textPropName) {
        valuePropName = valuePropName || "Value";
        textPropName = textPropName || "Text";

        var text = "";
        var len = optionList.length;
        for (var i = 0; i < len; i++) {
            if (optionList[i][valuePropName] == value) {
                text = optionList[i][textPropName];
                break;
            }
        }

        return text;
    }

    /* 依赖 bootstrap ui */
    $dh.selectRow = function (selectedTr) {
        var c = "warning";
        $(selectedTr).addClass(c);
        $(selectedTr).siblings().removeClass(c);
        return true;
    }
    $dh.formatBool = function (val) {
        if (val == true) {
            return "是";
        }
        else if (val == false) {
            return "否";
        }

        return val;
    }
    $dh.RespondStatusCode=function(result){
            //获取当前激活的url
        var $par = $(window.parent.document);
        var returnUrl= $par.find('.menuTabs').find('.active').attr('data-id');

            if (result == ResultStatus.Unauthorized) {
                //layerAlert(result.Msg || "权限不足，禁止访问");
                //return;
                //重定向登录页面
                window.location.href = '/Account/Login' + "?returnUrl=" + returnUrl;
            }
        
    
    }

    function execAjax(type, url, data, callback) {
        var layerIndex = layer.load(1);//加载中
        var ret = $.ajax({
            url: url,
            type: type,
            dataType: "json",
            data: data,
            complete: function (xhr) {
                layer.close(layerIndex);
            },
            success: function (result) {
                var isStandardResult = ("Status" in result) && ("Msg" in result);
                if (isStandardResult) {
                    if (result.Status == ResultStatus.Failed) {
                        layerAlert(result.Msg || "操作失败");
                        return;
                    }
                    //if (result.Status == ResultStatus.Unauthorized) {
                    //    //layerAlert(result.Msg || "权限不足，禁止访问");
                    //    //return;
                    //    //重定向登录页面
                    //    window.location.href = '/Account/Login';
                    //}
                    

                    if (result.Status == ResultStatus.OK) {
                        /* 传 result，用 result.Data 还是 result.Msg，由调用者决定 */
                        callback(result);
                    } else {
                        callback(result);
                    }
                }
                else
                    callback(result);
            },
            error: errorCallback
        });
        return ret;
    }
    function errorCallback(xhr, textStatus, errorThrown) {
        if (xhr.status == 401) {
            var $par = $(window.parent.document);
            var returnUrl = $par.find('.menuTabs').find('.active').attr('data-id');
            window.location.href = '/Account/Login' + "?returnUrl=" + returnUrl;
        } else {
            var json = { textStatus: textStatus, errorThrown: errorThrown };
            layerAlert("请求失败: " + JSON.stringify(json));
        }
        
    }
    function parseUrl(url) {
        if (url.indexOf("_dc=") < 0) {
            if (url.indexOf("?") >= 0) {
                url = url + "&_dc=" + (new Date().getTime());
            } else {
                url = url + "?_dc=" + (new Date().getTime());
            }
        }
        return url;
    };

    function layerAlert(msg, callBack) {
        msg = msg == null ? "" : msg;/* layer.alert 传 null 会报错 */
        var type = 'warning';
        var icon = "";
        if (type == 'success') {
            icon = "fa-check-circle";
        }
        if (type == 'error') {
            icon = "fa-times-circle";
        }
        if (type == 'warning') {
            icon = "fa-exclamation-circle";
        }

        var idx;
        idx = layer.alert(msg, {
            icon: icon,
            title: "系统提示",
            btn: ['确认'],
            btnclass: ['btn btn-primary'],
        }, function () {
            layer.close(idx);
            if (callBack)
                callBack();
        });
    }
    function layerConfirm(content, callBack) {
        var idx;
        idx = layer.confirm(content, {
            icon: "fa-exclamation-circle",
            title: "系统提示",
            btn: ['确认', '取消'],
            btnclass: ['btn btn-primary', 'btn btn-danger'],
        }, function () {
            layer.close(idx);
            callBack();
        }, function () {

        });
    }
    function layerMsg(msg, callBack) {
        msg = msg == null ? "" : msg;/* layer.msg 传 null 会报错 */
        layer.msg(msg, { time: 2000, shift: 0 });
    }


    window.$dh = $dh;
})($);


/* $ 扩展 */
(function ($) {

    /* 设置 input 标签的值，同时触发 change 事件 */
    $.fn.setValue = function (val) {
        this.val(val);
        this.change();
    }

    /* 根据值设置 select 标签的选中项，同时触发 change 事件 */
    $.fn.setSelectedValue = function (val) {
        for (var j = 0; j < this.length; j++) {
            var selectElement = this[j];
            for (var i = 0; i < selectElement.options.length; i++) {
                var op = selectElement.options[i];
                if (op.value == val) {
                    op.selected = true;
                    $(selectElement).change();
                    break;
                }
            }
        }
    };
    $.fn.getSelectedValue = function () {
        var ret = "";
        var c = "";
        for (var j = 0; j < this.length; j++) {
            var selectElement = this[j];
            var idx = selectElement.selectedIndex;
            ret += c + selectElement[idx].value;
            c = ";";
        }

        return ret;
    };
    $.fn.getSelectedText = function () {
        var ret = "";
        var c = "";
        for (var j = 0; j < this.length; j++) {
            var selectElement = this[j];
            var idx = selectElement.selectedIndex;
            ret += c + selectElement[idx].text;
            c = ";";
        }

        return ret;
    };

    $.fn.checked = function (value) {
        if (value == true)
            value = "true";
        else if (value == false)
            value = "false";

        for (var j = 0; j < this.length; j++) {
            var ele = this[j];
            if (value === undefined || value === null)
                ele.checked = true;
            else {
                if (ele.value == value)
                    ele.checked = true;
            }
        }
    }
    $.fn.checkedValue = function () {
        for (var j = 0; j < this.length; j++) {
            var ele = this[j];
            if (ele.checked == true) {
                return ele.value;
            }
        }

        return null;
    }

    //$.fn.formValid = function () {
    //    return $(this).valid({
    //        errorPlacement: function (error, element) {
    //            element.parents('.formValue').addClass('has-error');
    //            element.parents('.has-error').find('i.error').remove();
    //            element.parents('.has-error').append('<i id="ivalid" class="form-control-feedback fa fa-exclamation-circle error" data-placement="left" data-toggle="tooltip" title="' + error + '"></i>');                
    //            $("[data-toggle='tooltip']").tooltip();
    //            if (element.parents('.input-group').hasClass('input-group')) {
    //                element.parents('.has-error').find('i.error').css('right', '33px')
    //            }
    //        },
    //        success: function (element) {
    //            element.parents('.has-error').find('i.error').remove();
    //            element.parent().removeClass('has-error');
    //        }
    //    });
    //}

    $.fn.getFormData = function () {
        var element = $(this);
        var model = {};
        element.find('input,select,textarea').each(function (r) {
            var $this = $(this);
            var name = $this.attr('name');
            var type = $this.attr('type');
            switch (type) {
                case "checkbox":
                    model[name] = $this.is(":checked");
                    break;
                case "radio":
                    if (model[name] === undefined)
                        model[name] = null;
                    if (this.checked == true)
                        model[name] = this.value;
                    break;
                default:
                    var value = $this.val();
                    model[name] = value;
                    break;
            }
        });
        if ($('[name=__RequestVerificationToken]').length > 0) {
            model["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
        }
        return model;
    };
    $.fn.setFormData = function (data) {
        var element = $(this);
        element.find('input,select,textarea').each(function (r) {
            var $ele = $(this);
            var name = $ele.attr('name');
            var type = $ele.attr('type');

            var value = null;
            if (name in data)
                value = data[name];

            switch (type) {
                case "checkbox":
                    /* 先不管，回头在搞 */
                    //model[name] = $this.is(":checked");
                    break;
                case "radio":
                    if (value == true)
                        value = "true";
                    else if (value == false)
                        value = "false";
                    this.checked = this.value == value;
                    break;
                case "select":
                    $ele.val(value).trigger("change");
                    break;
                default:
                    $ele.val(value);
                    break;
            }
        });
    };

    $.fn.bindSelectWithData = function (options,callback) {
        var defaults = {
            value: "Id",
            text: "Name",
            change: null,
            items: [],
            placeholder: "--请选择--"
        };
        var options = $.extend(defaults, options);
        var $element = $(this);

        if (options.placeholder !== null && options.placeholder !== undefined)
            $element.append($("<option></option>").val("").html(options.placeholder));

        items = options.items;
        $.each(items, function (i) {
            $element.append($("<option></option>").val(items[i][options.value]).html(items[i][options.text]));
        });

        if (options.change)
            $element.change(options.change);

        callback(true);

        //return;
    }

    $.fn.bindSelectWithUrl = function (options, callback) {
        var defaults = {
            value: "Id",
            text: "Name",
            change: null,
            url: "",
            placeholder: "--请选择--",
            placeholderValue:''
        };
        var options = $.extend(defaults, options);
        var $element = $(this);
        $element.html("");

        if (options.placeholder !== null && options.placeholder !== undefined)
            $element.append($("<option></option>").val(options.placeholderValue).html(options.placeholder));

        $.ajax({
            type: "GET",
            url: options.url,
            dataType: "json",
            success: function (data) {
                $.each(data, function (i) {
                    $element.append($("<option></option>").val(data[i][options.value]).html(data[i][options.text]));
                });

                if (options.change)
                    $element.change(options.change);

                callback(true);

            }, error: function (xhr, textStatus, errorThrown) {
                callback(false);
            }
        });
        
    }

    $.fn.disable = function () {
        var $element = $(this);
        $element.attr("disabled", "disabled");
    }
    $.fn.enable = function () {
        var $element = $(this);
        $element.removeAttr("disabled");
    }

})($);

